<template>
    <basic-layout class="detBox" :title="tName" :showAddBtn="false">
        <!-- 介绍词 -->
        <div class="jscBox">
            &emsp;&emsp;{{ jsc }}
        </div>
        <!-- 进度条 -->
        <!-- <div v-if="isType" class="pgsBox">
            <van-progress :percentage="50" :show-pivot="false" />
            <div>1/2</div>
        </div> -->
        <!-- 主体 -->
        <div id="bodyWarp">
            <div class="subClass" v-for="(item,i) in topic" :key="i">
                <!-- 单选 -->
                <div class="wrapBox" v-if="item.itemType == 1">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                            <span class="isStars" v-if="item.required">*</span>
                            <span>{{ item.itemLabel }}</span>
                        </div>
                        <span>单选</span>
                    </div>
                    <van-radio-group class="padBox" v-model="item.answer">
                        <van-cell-group>
                            <van-cell v-for="(ra,i) in item.itemContent.arr" :key="i" clickable
                                @click="item.answer = ra.label">
                                <template #title>
                                    <van-radio :name="ra.label" />
                                    <span> {{ra.label}}</span>
                                </template>
                            </van-cell>
                        </van-cell-group>
                    </van-radio-group>
                </div>
                <!-- 多选 -->
                <div class="wrapBox" v-else-if="item.itemType == 2">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                            <span class="isStars" v-if="item.required">*</span>
                            <span>{{ item.itemLabel }}</span>
                        </div>
                        <span>多选</span>
                    </div>
                    <van-checkbox-group class="padBox" v-model="item.answer">
                        <van-cell-group>
                            <van-cell v-for="(ra,i) in item.itemContent.arr" :key="i" clickable @click="toggle(i)">
                                <template #title>
                                    <van-checkbox :name="ra.value" ref="checkboxes" shape="square" />
                                    <span>{{ra.label}}</span>
                                </template>
                            </van-cell>
                        </van-cell-group>
                    </van-checkbox-group>
                </div>
                <!-- 问答 -->
                <div class="wrapBox" v-else-if="item.itemType == 3">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                            <span class="isStars" v-if="item.required">*</span>
                            <span>{{ item.itemLabel }}</span>
                        </div>
                    </div>
                    <div class="padBox wdBox">
                        <van-field v-model="item.answer" rows="4" autosize type="textarea" placeholder="请输入内容" />
                    </div>
                </div>
                <!-- 日期 -->
                <div class="wrapBox" v-else-if="item.itemType == 4">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                        </div>
                    </div>
                    <date-page v-model="item.answer" :required="item.required" :itemLabel="item.itemLabel" />
                </div>
                <!-- 地区 -->
                <div class="wrapBox" v-else-if="item.itemType == 5">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                        </div>
                    </div>
                    <area-page v-model="item.answer" :required="item.required" :itemLabel="item.itemLabel" />
                </div>
                <!-- 单维 -->
                <div class="wrapBox" v-else-if="item.itemType == 6">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                        </div>
                        <span>单维</span>
                    </div>
                    <van-field class="rateBox">
                        <template #label>
                            <span class="isStars" v-if="item.required">*</span>
                            <span>{{ item.itemLabel }}</span>
                        </template>
                        <template #input>
                            <van-rate v-model="item.answer" :count="item.itemContent.arr.length" />
                        </template>
                    </van-field>
                </div>
                <!-- 多维 -->
                <div class="wrapBox" v-else-if="item.itemType === '7'">
                    <div class="titleBox">
                        <div class="leftBox">
                            <div>{{ item.itemNo }}</div>
                            <span class="isStars" v-if="item.required">*</span>
                            <span>{{ item.itemLabel }}</span>
                        </div>
                        <span>多维</span>
                    </div>
                    <van-field v-for="(dw,i) in item.itemContent.many" :key="'dw'+i" class="rateBox"
                        style="margin-bottom: 10px">
                        <template #label>
                            <span>{{ dw.key }}</span>
                        </template>
                        <template #input>
                            <van-rate v-model="dw.aFew" :count="dw.arr.length" />
                        </template>
                    </van-field>
                </div>
                <!-- 文本说明 -->
                <div class="textBox" v-if="item.itemType === '8'">
                    &emsp;&emsp;{{ item.placeholder }}
                </div>
            </div>
        </div>
        <!-- 按钮 -->
        <div v-if="isType" class="btnBox">
            <van-button round type="info" block @click="submitTo">提交问卷</van-button>
        </div>
    </basic-layout>
</template>

<script>
    import { getBrowserType, isTerminalType } from "./js/browser";
    import { detailsWJ, saveResult, isResultDetail, } from "@/api/platframe/questionnaire";
    export default {
        props: {},
        components: {
            'date-page': ()=> import('./components/calendar.vue'),
            'area-page': ()=> import('./components/areaCity.vue')
        },
        data() {
            return {
                isType: null, // true=>进行中
                tName: null, // 问卷名称
                jsc: null, // 介绍词
                topic: null, // 题目
                showDate: false, // 日期
                showArea: false, // 城市
            };
        },
        created() {
            let obj = JSON.parse(this.$route.query.params);
            this.isType = obj.isTF;
            // 根据传值，判断是进行中，还是完成了
            if (obj.isTF) {
                // 进行中
                this.wjID = obj.id;
                this.isStart = obj.time;
                this.getDetails(obj.id);
            } else {
                // 完成
                this.getResult(obj.resultId);
            }
        },
        mounted() {
            let dom0 = document.querySelector(".content");
            let dom1 = document.querySelector(".jscBox");
            let dom2 = document.getElementById("bodyWarp");
            if (this.isType) {
                dom2.style.height =
                    dom0.clientHeight - dom1.clientHeight - 90 - 38 + "px";
            } else {
                dom2.style.height =
                    dom0.clientHeight - dom1.clientHeight - 12 + "px";
                dom2.style.marginBottom = "10px";
            }
        },
        methods: {
            // 获取问卷详情
            async getDetails(id) {
                let res = await detailsWJ({ questionnaireId: id });
                if (res.code === 1000) {
                    this.tName = res.data.questionnaireName;
                    this.jsc = res.data.questionnaireDesc;
                    let objArr = [];
                    res.data.questionnaireItemList.forEach((element) => {
                        if (element.itemType == "7") {
                            // 多维评分
                            element.itemContent.many.forEach((ee) => {
                                ee.aFew = 0;
                            });
                            objArr.push(Object.assign(element));
                        } else if (element.itemType == "2") {
                            objArr.push(
                                Object.assign(element, { answer: [], choice: null })
                            );
                        } else {
                            objArr.push(
                                Object.assign(element, {
                                    answer: null,
                                    choice: null,
                                })
                            );
                        }
                    });
                    this.topic = objArr;
                }
            },
            // 提交问卷
            async submitTo() {
                if (this.isCheck()) {
                    let params = this.isObj();
                    Object.assign(params, {
                        browserType: getBrowserType(),
                        requestIp: '',
                        submitOs: isTerminalType(),
                    });

                    let res = await saveResult(params);
                    if (res.code === 1000) {
                        this.$Notify({ type: 'success', message: '提交成功！' });
                        this.$router.go(-1);
                    }
                } else {
                    this.$Notify({ type: 'error', message: '请完成必填项输入！' });
                }
            },
            // 完成问卷结果详情
            async getResult(id) {
                let res = await isResultDetail({ resultId: id });
                if (res.code == 1000) {
                    this.tName = res.data.questionnaireName;
                    this.jsc = res.data.questionnaireDesc;
                    this.topic = res.data.originalData.data;
                }
            },

            // 复选框赋值
            toggle(index) {
                this.$refs.checkboxes[index].toggle();
            },
            // 日期赋值
            onConfirm(date) {
                this.showDate = false;
                this.date = `${date.getMonth() + 1}/${date.getDate()}`;
            },

            // 校验
            isCheck() {
                let sumBTX = 0; // 必填项总和
                let sumFill = 0; // 填写必填项总和
                this.topic.forEach((e) => {
                    if (e.required) sumBTX++;
                    if (e.required && Boolean(e.answer)) sumFill++;
                });
                // 两个总和相等，则必填项都填了
                let isBoole = sumBTX == sumFill ? true : false;
                return isBoole;
            },
            // 处理提交条件
            isObj() {
                // 完成时间
                let wcTime = new Date().getTime() - this.isStart;
                wcTime = wcTime / 1000; // 相差秒数
                if (wcTime>60) {
                    let mm = Math.floor(wcTime/60); // 向下取整
                    let ss = Math.round(wcTime%60);
                    wcTime = mm+ '分' + ss + '秒';
                }else {
                    wcTime = Math.round(wcTime) + '秒';
                }

                // 单，多选题（包括下拉），单维评分，多维评分用于统计
                let listArr = [];
                this.topic.forEach((e) => {
                    if (e.itemType === "1") {
                        let aaa = [];
                        // console.log('单选题',e);
                        if (e.isDropdown) {
                            // 下拉单选题
                            if (e.answer != null) {
                                aaa.push(String(e.answer + 1));
                            }
                        } else {
                            for (const key in e.itemContent.arr) {
                                if (
                                    Object.hasOwnProperty.call(
                                        e.itemContent.arr,
                                        key
                                    )
                                ) {
                                    const element = e.itemContent.arr[key];
                                    if (e.answer == element.label) {
                                        aaa.push(String(Number(key) + 1));
                                    }
                                }
                            }
                        }
                        // 用于后台统计 choice itemSelection
                        e.choice = aaa;
                        listArr.push({
                            'itemId': e.itemId,
                            'itemSelection': aaa,
                        });
                    } else if (e.itemType === "2") {
                        // console.log('多选题',e);
                        let aaa = [];
                        if (e.answer && e.answer.length > 0) {
                            e.answer.forEach((val) => {
                                aaa.push(String(val + 1));
                            });
                        }

                        e.choice = aaa;
                        listArr.push({
                            'itemId': e.itemId,
                            'itemSelection': aaa,
                        });
                    } else if (e.itemType === "6") {
                        // console.log('单维评分',e);
                        e.choice = String(e.answer);
                        listArr.push({
                            'itemId': e.itemId,
                            'itemSelection': e.answer? [String(e.answer)] : [],
                        });
                    } else if (e.itemType === "7") {
                        // console.log('多维评分',e);
                        let aaa = [];
                        e.itemContent.many.forEach((val) => {
                            if (val.aFew != 0) {
                                aaa.push(String(val.aFew))
                            }
                        });
                        e.choice = aaa;
                        listArr.push({
                            'itemId': e.itemId,
                            'itemSelection': aaa,
                        });
                    }
                });
                // 保存条件
                let obj = {
                    completeTime: wcTime,
                    questionnaireId: this.wjID,
                    originalData: { data: this.topic }, // 题目相关数据
                    questionnaireResultItemList: listArr,
                };
                // console.log("提交条件", obj);
                return obj;
            },
        },
    };
</script>

<style scoped lang="less">
    .detBox ::v-deep .content {
        background-color: #ebebeb;
    }
    // 介绍词
    .jscBox {
        padding: 10px 16px;
        background-color: #fff;
    }
    // 进度条
    .pgsBox {
        height: 36px;
        padding: 0 16px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        background-color: #fff;
        .van-progress {
            // margin-top: 10px;
            width: 88%;
        }
        > div:nth-child(2) {
            width: 30px;
            color: #3083ff;
        }
    }
    // 主体部分
    #bodyWarp {
        overflow: auto;
        padding: 0 16px 80px;
        .wrapBox {
            margin-top: 10px;
            background-color: #fff;
            .titleBox {
                padding: 0 10px 5px 0;
                display: flex;
                align-items: center;
                justify-content: space-between;
                > span {
                    color: #2b7cff;
                }
                .leftBox {
                    display: flex;
                    align-items: center;
                    > div:nth-child(1) {
                        width: 36px;
                        height: 36px;
                        line-height: 36px;
                        text-align: center;
                        font-size: 14px;
                        font-weight: bold;
                        color: #fff;
                        background-color: #227fff;
                        margin-right: 8px;
                        border-bottom-right-radius: 22px;
                    }
                    > span {
                        color: #474747;
                    }
                }
            }
            .padBox {
                padding: 0 10px 10px;
            }
            
            .van-radio-group,
            .van-cell-group {
                .van-cell__title {
                    display: flex;
                    > span {
                        margin-left: 8px;
                    }
                }
            }
            .wdBox ::v-deep .van-field {
                background-color: #f1f1f1;
            }
            .rateBox {
                padding: 10px !important;
                background-color: #fff;
            }
        }
        .textBox {
            min-height: 70px;
            padding: 8px 10px;
            background-color: #fff;
        }
        
        .isStars {
            color: red !important;
            margin-right: 6px;
        }
    }
    // 按钮
    .btnBox {
        width: 90%;
        position: fixed;
        bottom: 20px;
        left: 5%;
    }
</style>